import { login } from '@/common/apis/common';
import { getUserInfo } from '@/common/apis/user';
const token: string | null = localStorage.getItem('qcdxs_token');

export default {
    namespace: true,
    state: {
        token: token,
        userInfo: null
    },
    mutations: {
        SET_TOKEN: (state: any, token: string) => {
            state.token = token;
            localStorage.setItem('qcdxs_token', token);
        },
        SET_USERINFO: (state: any, userInfo: object) => {
            state.userInfo = userInfo;
        }
    },

    actions: {
        // 登录
        login(context: any, userInfo: any) {
            return new Promise((resolve, reject) => {
                login(userInfo).then((res: any) => {
                    context.commit('SET_TOKEN', res.token)
                    resolve(res.token)
                }).catch((error: any) => {
                    reject(error)
                })
            })
        },
        /**
         * 获取用户信息
         */
        getUserInfo(context: any) {
            return new Promise((resolve, reject) => {
                getUserInfo().then((res: any) => {
                    context.comit('SET_USERINFO', res.data);
                    resolve(res.data);
                }).catch((error: any) => {
                    reject(error);
                })
            })
        }
    }
}
